#include "connect.h"
#include "image.h"

/**
 * Receive and interpolate a stream of Gaussian images of dimensione width x heigth.
 */

int main (int argc, char* argv []) {

    int i = 0;
    
    /* parameters to be inizialized */
    int width = 0, heigth = 0, stream = 0, dim = 0;
    unsigned char* image = NULL;
    
#ifdef PERFORMANCE
    struct timeval time_1, time_2;
#endif
    
#ifdef DEBUG
#define PATH_OPERAZIONI "./Debug/Gaussian_"
#define DIM 30
    char path [DIM];
    char numim [DIM];
#endif
    
#ifndef NOCAMERA
    
    /* receive the parameters */
    int sock = Connect();
    if (Read (sock, &width, sizeof (int)) < 0)
        error ("Error readinf the width");
    if (Read (sock, &heigth, sizeof (int)) < 0)
        error ("Error reading the heigth");
    if (Read (sock, &stream, sizeof (int)) < 0)
        error ("Error reading the length of the stream");
    
#else
    
    /* initialize the parametrs with default values */
#define DEFAULTWIDTH 1024
#define DEFAULTHEIGTH 1024
#define DEFAULTSTREAM 50

    width = DEFAULTWIDTH;
    heigth = DEFAULTHEIGTH;
    stream = DEFAULTSTREAM;
    
#endif
    
    dim = width * heigth;    

    
#ifndef NOCAMERA
    
    /* if the images came from an external camera we allocate the buffer only here */
    image = (unsigned char*) malloc (dim);
    
#endif
    
    /* start the loop on images */
    for (i = 0; i < stream; i++) {

#ifndef NOCAMERA
        
        /* if the external camera is present we receive the image from the socket */
        if (Read (sock, image, dim) < dim)
            error ("Error reading the image");

#else
        
        /* in case local images are created we allocated every time the buffer ... */
        image = createImage (width, heigth);
        
#endif

        if (i == 0) {

            /* perform the initialization for starting the interpolation */
            
            
#ifdef PERFORMANCE

            /* take the time at the first iteration */
            gettimeofday (&time_1, NULL);

#endif

        }

        


        
#ifdef DEBUG
        
        /* create the path */
        strcpy (path, PATH_OPERAZIONI);
		sprintf(numim, "%d", i);
		strcat (path, numim);
		strcat (path, ".tiff");
        
        /* write the image */
        writeImage (image, path, width, heigth);

#endif
        
        /* WORK on images */
        
        /* END WORK on images */
        
#ifdef NOCAMERA
        
        /* ... and consequently we deallocate */
        free (image);
        
#endif
        
    }
    
#ifdef PERFORMANCE
    
    /* take the time and compute the difference */
    gettimeofday (&time_2, NULL);
    printf ("\nCompletion time: %ld microseconds\n", getCompletionTime (&time_1, &time_2));
    
#endif
    
    return 0;
}